/*
 * @Date: 2022-02-12 12:29:22
 * @LastEditors: tich425
 * @LastEditTime: 2022-02-12 16:59:02
 * @FilePath: \TodoList\service\todo.go
 * @Description: todo 处理
 */
package service

import (
	"todo-list/global"
	"todo-list/model"
	"todo-list/res"
	"todo-list/utils"

	"github.com/gin-gonic/gin"
)

/**
 * @description: 查看全部便签
 * @param {uint} uid
 * @param {int} page
 * @param {*gin.Context} c
 */
func AllTodo(uid uint, page int, c *gin.Context) {
	// 取得全部信息
	var raw []model.Todo
	global.MYSQL_DB.Where("uid = ?", uid).Limit(8).Offset(8 * (page - 1)).Find(&raw)

	// 判断是否创建便签
	if len(raw) == 0 {
		res.FailWithMessage(res.NotFind, "用户尚未创建便签", c)
		return
	}

	// 信息传输
	var data []model.TodoDto
	for _, t := range raw {
		var td model.TodoDto
		utils.StructAssign(&td, &t)
		td.ID = t.ID // 传入用户ID
		data = append(data, td)
	}

	// 返回信息
	res.OkWithData(data, c)
}

/**
 * @description: 添加便签处理
 * @param {model.Todo} t
 * @param {*gin.Context} c
 */
func AddTodo(t model.Todo, c *gin.Context) {
	// 保存到数据库
	global.MYSQL_DB.Create(&t)

	res.OkWithData(gin.H{"tid": t.ID}, c)
}

/**
 * @description: 搜索便签处理
 * @param {uint} uid
 * @param {string} t
 * @param {int} page
 * @param {*gin.Context} c
 */
func SearchTodo(uid uint, t string, page int, c *gin.Context) {
	// 搜索信息
	var raw []model.Todo
	global.MYSQL_DB.Where("uid = ? and title LIKE ? ", uid, "%"+t+"%").Order("id desc").Find(&raw)

	// 未查询到便签的错误处理
	if len(raw) == 0 {
		res.FailWithMessage(res.NotFind, "什么都没找到", c)
		return
	}

	// 信息传输
	var data []model.TodoDto
	for _, t := range raw {
		var td model.TodoDto
		utils.StructAssign(&td, &t)
		td.ID = t.ID
		data = append(data, td)
	}

	// 返回信息
	res.OkWithData(data, c)
}

/**
 * @description: 修改便签处理
 * @param {uint} uid
 * @param {model.TodoDto} td
 * @param {*gin.Context} c
 */
func UpdateTodo(uid uint, td model.TodoDto, c *gin.Context) {
	// 获取便签
	var todo model.Todo
	global.MYSQL_DB.First(&todo, td.ID)

	// 判断文章所有权
	if uid != todo.UID {
		res.FailWithMessage(res.NoAuth, "无权限", c)
		return
	}

	// 数据传输
	utils.StructAssign(&todo, &td)

	// 保存到数据库
	global.MYSQL_DB.Save(&todo)

	// 返回信息
	res.OkWithData(gin.H{"tid": todo.ID}, c)
}

/**
 * @description: 删除便签处理
 * @param {uint} uid
 * @param {uint} tid
 * @param {*gin.Context} c
 */
func RemoveTodo(uid uint, tid uint, c *gin.Context) {
	// 获取便签
	var todo model.Todo
	global.MYSQL_DB.First(&todo, tid)

	// 判断文章所有权
	if uid != todo.UID {
		res.FailWithMessage(res.NoAuth, "无权限", c)
		return
	}

	// 删除便签
	global.MYSQL_DB.Where("id = ?", tid).Delete(&model.Todo{})

	// 返回信息
	res.OkWithData(gin.H{"tid": todo.ID}, c)
}
